import requests
import json
from openpyxl import Workbook

wb = Workbook()#实例化工作表
ws=wb.active#激活工作表
ws.append(["房间名","主播名","房间名","热度"])#增加表头

#准备headers和url
headers={
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62"
}
url="https://www.huya.com/cache.php?m=LiveList&do=getLiveListByPage&gameId=2168&tagAll=0&callback=getLiveListJsonpCallback&page=2"
#创建参数字典
params={
   "m": "LiveList",
   "do": "getLiveListByPage",
   "gameId": "2168",
   "tagAll":"0",
   # "callback": "getLiveListJsonpCallback",
}
for page in range(1,4):
    params["page"]=page
    response = requests.get(url,headers=headers,params=params)
    ret = response.text
    ret = ret[25:-1]
    ret = json.loads(ret)["data"]["datas"]
    for i in ret :
        room = i["roomName"]
        name = i["nick"]
        roomnum=i["profileRoom"]
        hot = str(round(int(i["totalCount"])/10000,2))
        ws.append([room,name,roomnum,hot])
        print("房间名：{},主播名：{},房间号：{}，热度：{}万".format(room,name,roomnum,hot))
wb.save("data/虎牙颜值区房间数据.xlsx")


    # with open("./data/huya颜值区第{}页.text".format(page),"w",encoding="utf-8") as f:
    #     f.write(response.content.decode("utf-8"))
